﻿using MediatR;
using ProduceBasicData.Api.Application.Command.Supplier;
using ProduceBasicData.Api.DTO;
using ProduceBasicData.Domain.Material;
using ProduceBasicData.Domain.WarehouseManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.Supplier
{
    /// <summary>
    /// 供应商信息获取处理
    /// </summary>
    public class GetSupplierHandler : IRequestHandler<GetSupplierCommand, ApiPaging<SupplierDto>>
    {
        private readonly IBaseRespository<SupplierModel> supplierRepo;
        private readonly IBaseRespository<Warehouse> wareRepo;

        public GetSupplierHandler(IBaseRespository<SupplierModel> supplierRepo,
            IBaseRespository<Warehouse> wareRepo)
        {
            this.supplierRepo = supplierRepo;
            this.wareRepo = wareRepo;
        }

        public Task<ApiPaging<SupplierDto>> Handle(GetSupplierCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<SupplierDto> res=new ApiPaging<SupplierDto>();

            var supplier = supplierRepo.GetAll().Where(x=>!x.Isdel);
            var ware = wareRepo.GetAll().Where(x => !x.Isdel);


            var linq = from a in supplier
                       join b in ware on a.WarehouseId equals b.Id
                       select new SupplierDto
                       {
                           Id = a.Id,
                           CompanAddr=a.CompanAddr,
                           Code = a.Code,
                           CompanName=a.CompanName,
                           Desc=a.Desc,
                           Name=a.Name,
                           SocialCreditCode=a.SocialCreditCode,
                           Tel=a.Tel,
                           WarehouseId=a.WarehouseId,
                           WarehouseName=b.Name,
                           CreateName=a.CreateName,
                           CreateTime=a.CreateTime,
                           UpdateName=a.UpdateName,
                           UpdateTime=a.UpdateTime,
                       };
            res.PageDatas=linq.OrderByDescending(x=>x.Id).Skip((request.Index-1)*request.Size).Take(request.Size).ToList();
            res.TotalCount = linq.Count();
            res.Code = ApiEnum.Success;
            res.Msg = "供应商信息查询成功";
            return Task.FromResult(res);
        }
    }
}
